<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    header('Location: index.php');
    exit;
}

require_once __DIR__ . '/../core/config.php';
try {
    $db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET, DB_USER, DB_PASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $db->query("SELECT * FROM plugins ORDER BY created_at DESC");
    $plugins = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt = $db->query("SELECT * FROM categories ORDER BY name");
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo '<div class="bg-red-100 text-red-700 p-4 rounded mb-4">SQL错误：' . htmlspecialchars($e->getMessage()) . '</div>';
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>插件管理 - 幻影工具网</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- 顶部导航 -->
    <nav class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-10">
        <div class="max-w-7xl mx-auto px-4 flex justify-between items-center h-16">
            <h1 class="text-xl font-bold text-blue-700">幻影工具网后台</h1>
            <div class="flex items-center space-x-4">
                <a href="/" class="text-gray-600 hover:text-blue-700">返回前台</a>
                <a href="logout.php" class="text-red-600 hover:text-red-800">退出登录</a>
            </div>
        </div>
    </nav>
    <div class="flex min-h-screen">
        <!-- 侧边栏 -->
        <aside class="w-64 bg-white shadow-md hidden md:block">
            <nav class="mt-8 space-y-2 px-4">
                <a href="index.php" class="block px-4 py-2 rounded-lg text-gray-600 hover:bg-blue-50 hover:text-blue-700">仪表盘</a>
                <a href="plugins.php" class="block px-4 py-2 rounded-lg bg-blue-50 text-blue-700 font-bold">插件管理</a>
                <a href="categories.php" class="block px-4 py-2 rounded-lg text-gray-600 hover:bg-blue-50 hover:text-blue-700">分类管理</a>
                <a href="stats.php" class="block px-4 py-2 rounded-lg text-gray-600 hover:bg-blue-50 hover:text-blue-700">数据统计</a>
                <a href="logs.php" class="block px-4 py-2 rounded-lg text-gray-600 hover:bg-blue-50 hover:text-blue-700">操作日志</a>
            </nav>
        </aside>
        <!-- 主内容区 -->
        <main class="flex-1 p-6">
            <div class="mb-8">
                <h2 class="text-2xl font-bold text-gray-900 mb-2">插件管理</h2>
                <p class="text-gray-500">管理所有插件，包括启用、禁用、编辑、设置分类、删除等功能</p>
            </div>
            <!-- 操作按钮 -->
            <div class="mb-6 flex flex-wrap gap-4">
                <button onclick="openUploadModal()" class="bg-blue-600 text-white px-5 py-2 rounded-lg shadow hover:bg-blue-700 transition">上传插件</button>
                <button onclick="syncPlugins()" class="bg-green-600 text-white px-5 py-2 rounded-lg shadow hover:bg-green-700 transition">同步插件</button>
            </div>
            <!-- 插件列表 -->
            <div class="bg-white rounded-xl shadow p-4 overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">插件信息</th>
                            <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">状态</th>
                            <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">统计</th>
                            <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-100">
                        <?php foreach ($plugins as $plugin): ?>
                        <?php
                            $status = $plugin['status'] ?? 'inactive';
                            $views = $plugin['views'] ?? 0;
                            $likes = $plugin['likes'] ?? 0;
                            $folder = $plugin['folder'] ?? '';
                            if (!$folder) $folder = 'default';
                        ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0 h-10 w-10">
                                        <img class="h-10 w-10 rounded-lg" src="/plugins/<?php echo $folder; ?>/icon.svg" alt="<?php echo htmlspecialchars($plugin['name']); ?>">
                                    </div>
                                    <div class="ml-4">
                                        <div class="text-sm font-bold text-gray-900"><?php echo htmlspecialchars($plugin['name']); ?></div>
                                        <div class="text-xs text-gray-500"><?php echo htmlspecialchars($plugin['description']); ?></div>
                                        <div class="text-xs text-gray-400">版本: <?php echo htmlspecialchars($plugin['version']); ?></div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <?php if ($status === 'active'): ?>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">已启用</span>
                                <?php else: ?>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">已禁用</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <div>浏览量: <?php echo number_format($views); ?></div>
                                <div>点赞数: <?php echo number_format($likes); ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <div class="flex space-x-2">
                                    <?php if ($status === 'inactive'): ?>
                                        <button onclick="togglePlugin(<?php echo $plugin['id']; ?>, 'inactive')" class="text-yellow-600 hover:text-yellow-900">启用</button>
                                    <?php else: ?>
                                        <button onclick="togglePlugin(<?php echo $plugin['id']; ?>, 'active')" class="text-green-600 hover:text-green-900">禁用</button>
                                    <?php endif; ?>
                                    <button onclick="editPlugin(<?php echo $plugin['id']; ?>)" class="text-blue-600 hover:text-blue-900">编辑</button>
                                    <button onclick="setCategory(<?php echo $plugin['id']; ?>)" class="text-purple-600 hover:text-purple-900">分类</button>
                                    <button onclick="deletePlugin(<?php echo $plugin['id']; ?>)" class="text-red-600 hover:text-red-900">删除</button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <!-- 上传插件模态框 -->
            <div id="uploadModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
                <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                    <div class="mt-3">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">上传插件</h3>
                        <form id="uploadForm" enctype="multipart/form-data">
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">选择插件文件 (ZIP格式)</label>
                                <input type="file" name="plugin_file" accept=".zip" class="w-full border border-gray-300 rounded-md px-3 py-2" required>
                            </div>
                            <div class="flex justify-end space-x-3">
                                <button type="button" onclick="closeUploadModal()" class="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50">取消</button>
                                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">上传</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <!-- 设置分类模态框 -->
            <div id="categoryModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
                <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                    <div class="mt-3">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">设置分类</h3>
                        <form id="categoryForm">
                            <input type="hidden" id="pluginId" name="plugin_id">
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2">选择分类</label>
                                <select name="category_id" class="w-full border border-gray-300 rounded-md px-3 py-2">
                                    <option value="">无分类</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?php echo $category['id']; ?>"><?php echo htmlspecialchars($category['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="flex justify-end space-x-3">
                                <button type="button" onclick="closeCategoryModal()" class="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50">取消</button>
                                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <script>
                // 上传插件
                function openUploadModal() {
                    document.getElementById('uploadModal').classList.remove('hidden');
                }
                function closeUploadModal() {
                    document.getElementById('uploadModal').classList.add('hidden');
                }
                document.getElementById('uploadForm').addEventListener('submit', function(e) {
                    e.preventDefault();
                    const formData = new FormData(this);
                    fetch('ajax.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('插件上传成功！');
                            location.reload();
                        } else {
                            alert('上传失败：' + data.message);
                        }
                    });
                });
                // 同步插件
                function syncPlugins() {
                    if (confirm('确定要同步插件吗？这将重新扫描插件目录。')) {
                        fetch('ajax.php', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                            body: 'action=sync_plugins'
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                alert('插件同步成功！');
                                location.reload();
                            } else {
                                alert('同步失败：' + data.message);
                            }
                        });
                    }
                }
                // 切换插件状态
                function togglePlugin(id, status) {
                    fetch('ajax.php', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: `action=toggle_plugin&id=${id}&status=${status}`
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            location.reload();
                        } else {
                            alert('操作失败：' + data.message);
                        }
                    });
                }
                // 编辑插件
                function editPlugin(id) {
                    window.open(`plugin_edit.php?id=${id}`, '_blank');
                }
                // 设置分类
                function setCategory(id) {
                    document.getElementById('pluginId').value = id;
                    document.getElementById('categoryModal').classList.remove('hidden');
                }
                function closeCategoryModal() {
                    document.getElementById('categoryModal').classList.add('hidden');
                }
                document.getElementById('categoryForm').addEventListener('submit', function(e) {
                    e.preventDefault();
                    const formData = new FormData(this);
                    formData.append('action', 'set_plugin_category');
                    fetch('ajax.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('分类设置成功！');
                            closeCategoryModal();
                        } else {
                            alert('设置失败：' + data.message);
                        }
                    });
                });
                // 删除插件
                function deletePlugin(id) {
                    if (confirm('确定要删除这个插件吗？此操作不可恢复。')) {
                        fetch('ajax.php', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                            body: `action=delete_plugin&id=${id}`
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                location.reload();
                            } else {
                                alert('删除失败：' + data.message);
                            }
                        });
                    }
                }
            </script>
        </main>
    </div>
</body>
</html> 